#include "MovingWindowPositionBased.h"

using namespace std;

SetID_pos::SetID_pos(vector<MapField*> vec, unsigned int window, unsigned int step){
	int setid_index = 0;
	vector<MapField*>::iterator checkpoint;
	bool checkpoint_flag = false;
	bool initialized_flag = false;
	
	// initialize coordinates
	unsigned int window_start = 0;
	unsigned int window_end = window;
	
	// loop
	auto curr = vec.begin(), next = curr+1;
	for (; 
		next != vec.end(); 
		curr++, next++)
	{
		// chr 0 and mito has one set each		
		if ( (*curr)->get_chr() == 0 || (*curr)->get_chr() == 26){
			setidvec.push_back(new MarkerSet(setid_index, *curr));
		}
		// if curr and next are on the same chr, check pos
		else if ( (*curr)->get_chr() == (*next)->get_chr() ){
			// if window end is not reached
			if (!initialized_flag){
				while ( (*curr)->get_pos() > window_end){
					window_start+=step;
					window_end+=step;
					// once data is reached, add first element and flag initialized_flag
				}
					setidvec.push_back(new MarkerSet(setid_index, *curr));
					initialized_flag = true;
			}
			else if ((*curr)->get_pos() <= window_end){
				setidvec.push_back(new MarkerSet(setid_index, *curr));
				// save checkpoint when going past start point for the next window
				if ((*curr)->get_pos() >= (window_start + step) && !checkpoint_flag){
					checkpoint = curr;
					checkpoint_flag = true;
				}
			}
			// if window end is reached, move window forward and move curr pointer to the first marker at start
			// of the new window
			else if ((*curr)->get_pos() > window_end){
				window_start+=step;
				window_end+=step;
				setid_index++;
				if (checkpoint_flag){
					curr = checkpoint;
					next = checkpoint+1;
					checkpoint_flag = false;
					setidvec.push_back(new MarkerSet(setid_index, *curr));
				}
				else {
					setidvec.push_back(new MarkerSet(setid_index, *curr));
				
				}
			}
		}
		// if curr and next are on different chr, put curr in the current setid
		// then increment set id and restart window position
		else {
			setidvec.push_back(new MarkerSet(setid_index, *curr));
			setid_index++;
			initialized_flag = false;
			window_start = 0;
			window_end = window;
		}
	
	}
	setidvec.push_back(new MarkerSet(setid_index, *curr));
}

